﻿using CoreModule;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Threading;
namespace IdResourceModule.Views
{
    /// <summary>
    /// ChartAgeControl.xaml 的交互逻辑
    /// </summary>
    public partial class ChartAgeControl : UserControl, INotifyPropertyChanged
    {
        CoreModule.Storages.DbStorage DbStorage { get; set; }
        public ChartAgeControl(CoreModule.Storages.DbStorage dbStorage,IDeviceManager deviceManager)
        {
            InitializeComponent();
            DbStorage = dbStorage;
            DataContext = this;
            try
            {
                RefreshData();
            }catch (Exception)
            {
            }
            deviceManager.MeasurementResultCompletedInManagementModule += DeviceManager_MeasurementResultCompletedInManagementModule;
        }
        private void DeviceManager_MeasurementResultCompletedInManagementModule(object sender, MeasurementResultInfoEventArgs e)
        {
            RefreshData();
        }
        private SeriesCollection seriesCollection;
        public SeriesCollection SeriesCollection
        {
            get { return seriesCollection; }
            set { seriesCollection = value; OnPropertyChanged(nameof(SeriesCollection)); }
        }
        public string ToolTipText { get; set; }
        public object SelectedItem { get; set; }
        private int total = 0;
        private int minorityCount;
        public int MinorityCount
        {
            get { return minorityCount; }
            set { minorityCount = value; OnPropertyChanged(nameof(MinorityCount)); OnPropertyChanged(nameof(MinorityPercent)); }
        }
        public string MinorityPercent
        {
            get { return $"{(minorityCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        private int middleAgeCount;
        public int MiddleAgeCount
        {
            get { return middleAgeCount; }
            set { middleAgeCount = value; OnPropertyChanged(nameof(MiddleAgeCount)); OnPropertyChanged(nameof(MiddleAgePercent)); }
        }
        public string MiddleAgePercent
        {
            get { return $"{(middleAgeCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        private int youthCount;
        public int YouthCount
        {
            get { return youthCount; }
            set { youthCount = value; OnPropertyChanged(nameof(YouthCount)); OnPropertyChanged(nameof(YouthPercent)); }
        }
        public string YouthPercent
        {
            get { return $"{(youthCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        private int oldAgeCount;
        public int OldAgeCount
        {
            get { return oldAgeCount; }
            set { oldAgeCount = value; OnPropertyChanged(nameof(OldAgeCount)); OnPropertyChanged(nameof(OldAgePercent)); }
        }
        public string OldAgePercent
        {
            get { return $"{(oldAgeCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        private int unknowCount;
        public int UnknowCount
        {
            get { return unknowCount; }
            set { unknowCount = value; OnPropertyChanged(nameof(UnknowCount)); }
        }
        public void RefreshData()
        {
            var String_Not_Yet_Of_Age = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Not_Yet_Of_Age", null, null) + "";

            var String_Old_Age = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Old_Age", null, null) + "";

            var String_Mid_Age = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Mid_Age", null, null) + "";

            var String_Youth = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Youth", null, null) + "";

            var String_Unknown = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Unknown", null, null) + "";


            var dbContext = DbStorage;
           
                if (dbContext.PatientInfos.Count() > 0)
                {
                    imgEmpty.Visibility = Visibility.Collapsed;
                    gridChart.Visibility = Visibility.Visible;
                    chartAge.Visibility = Visibility.Visible;
                }
                else
                {
                    return;
                }
                total = dbContext.PatientInfos.Count();
                MinorityCount = dbContext.PatientInfos.Count(it => it.Age < 18);
                YouthCount = dbContext.PatientInfos.Count(it => it.Age >= 18 && it.Age < 36);
                MiddleAgeCount = dbContext.PatientInfos.Count(it => it.Age >= 36 && it.Age < 60);
                OldAgeCount = dbContext.PatientInfos.Count(it => it.Age >= 60);
                UnknowCount = dbContext.PatientInfos.Count(it => it.Age==0);
            if (SeriesCollection == null)
            {
              
               

                SeriesCollection = new SeriesCollection
                    {
                        new PieSeries
                        {
                            Title = String_Not_Yet_Of_Age,
                            Values = new ChartValues<ObservableValue> { new ObservableValue(minorityCount) },
                            DataLabels = false,
                            Fill = new SolidColorBrush(Color.FromRgb(175,175,175))
                        },
                        new PieSeries
                        {
                            Title = String_Old_Age,
                            Values = new ChartValues<ObservableValue> { new ObservableValue(oldAgeCount) },
                            DataLabels = false,
                            Fill = new SolidColorBrush(Color.FromRgb(39,138,140))
                        },
                        new PieSeries
                        {
                            Title =String_Mid_Age,
                            Values = new ChartValues<ObservableValue> { new ObservableValue(middleAgeCount) },
                            DataLabels = false,
                            Fill = new SolidColorBrush(Color.FromRgb(182,8,36))
                        },
                        new PieSeries
                        {
                            Title = String_Youth,
                            Values = new ChartValues<ObservableValue> { new ObservableValue(youthCount) },
                            DataLabels = false,
                            Fill = new SolidColorBrush(Color.FromRgb(52,91,155))
                        },
                        new PieSeries
                        {
                            Title = String_Unknown,
                            Values = new ChartValues<ObservableValue> { new ObservableValue(unknowCount) },
                            DataLabels = false,
                            Fill = new SolidColorBrush(Color.FromRgb(202,202,202))
                        }
                    };
            }
            else
            {
                foreach (var series in SeriesCollection)
                {
                    if (series.Title == String_Not_Yet_Of_Age)
                    {
                        series.Values.Cast<ObservableValue>().ElementAt(0).Value = minorityCount;
                    }
                    else if (series.Title == String_Youth)
                    {
                        series.Values.Cast<ObservableValue>().ElementAt(0).Value = youthCount;
                    }
                    else if (series.Title == String_Mid_Age)
                    {
                        series.Values.Cast<ObservableValue>().ElementAt(0).Value = middleAgeCount;
                    }
                    else if (series.Title == String_Old_Age)
                    {
                        series.Values.Cast<ObservableValue>().ElementAt(0).Value = oldAgeCount;
                    }
                    else if (series.Title == String_Unknown)
                    {
                        series.Values.Cast<ObservableValue>().ElementAt(0).Value = unknowCount;
                    }
                }
            };
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private void chartAge_Loaded(object sender, RoutedEventArgs e)
        {
        
            // 延迟操作的执行，直到控件完全渲染
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                var animation = new DoubleAnimation
                {
                    From = 0,
                    To = 0.9,
                    Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                    BeginTime = TimeSpan.FromSeconds(0.3)
                };
                var animationShadow = new DoubleAnimation
                {
                    From = 0,
                    To = 0.5,
                    Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                    BeginTime = TimeSpan.FromSeconds(0.3)
                };
                borderMinority.BeginAnimation(UIElement.OpacityProperty, animation);
                borderMinorityShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
                borderOldAge.BeginAnimation(UIElement.OpacityProperty, animation);
                borderOldAgeShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
                borderYouth.BeginAnimation(UIElement.OpacityProperty, animation);
                borderYouthShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
                borderMiddleAge.BeginAnimation(UIElement.OpacityProperty, animation);
                borderMiddleAgeShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
            }));
        }
        private void gridChart_Loaded(object sender, RoutedEventArgs e)
        {
        }
    }
}
